<template>
  <div class="flex-1 overflow-hidden flex flex-col w-[290px]" :class="{ 'disabled-style': loading }">
    <!--患者列表 -->
    <SearchComb v-model:value="searchState" :show-date="!store.isCallConfig" placeholder="姓名/助记码/卡号/手机号/身份证号/排队号" @search="search()" />
    <div class="my-2">
      <a-radio-group v-model:value="state" button-style="solid" class="flex radio-style" @change="onChangeActive()">
        <a-radio-button v-for="(item, index) in searchButton" :key="index" :value="item.state">
          <span class="text-xs">{{ item.title }}({{ item.count || 0 }})</span>
        </a-radio-button>
      </a-radio-group>
    </div>
    <BaseList :data-source="dataSource" :loading="loading" class="w-full flex-1 overflow-auto">
      <template #renderItem="{ item }">
        <div class="py-3 px-3 !mt-0" :class="selectedItem?.jzbh === item.jzbh ? 'active' : ''" @click="onSelect(item)">
          <div class="flex justify-between items-center">
            <div class="w-3/5">
              <div class="text-base font-bold text-primary truncate mb-2 flex items-center" :title="item.brName">
                <div class="max-w-20 truncate mr-2">{{ item.brName }}</div>
                <a-button v-if="item.czfz === '初诊'" type="primary" shape="circle" size="small">初</a-button>
                <a-button v-if="item.czfz === '复诊'" type="primary" shape="circle" size="small" class="bg-orange-400">复</a-button>
                <a-dropdown placement="bottomLeft">
                  <template #overlay>
                    <a-card class="w-[215px]">
                      <div class="flex mb-2">
                        <LabelValue :width="140" class="mr-2" :value="referralData?.originalEmpName" />
                        <LabelValue :value="referralData?.addtime" />
                      </div>
                      <div>{{ referralData?.memo ? referralData?.memo : '-' }}</div>
                    </a-card>
                  </template>
                  <a-button
                    v-if="item.sfzz === '1'"
                    type="primary"
                    shape="circle"
                    size="small"
                    class="bg-lime-500 ml-1"
                    @mouseenter="handlerReferral(item.jzbh)"
                    >转</a-button
                  >
                </a-dropdown>
              </div>
              <span class="w-14 text-grey mr-2">{{ item.brXb }}</span>
              <span class="text-right text-grey mr-2">{{ item.brAge }}</span>
              <span class="inline-block w-[90px] text-left text-grey truncate align-top">{{ item.matterName }}</span>
            </div>
            <div class="flex items-center justify-end w-2/5 overflow-hidden">
              <div v-if="store.isCallConfig" class="text-right">
                <!-- <div class="text-base mb-2">{{ item.lsh }}</div> -->
                <div class="text-base mb-2">{{ item.queueNo || '-' }}</div>
                <div class="text-grey">{{ item.rysx || '-' }}</div>
              </div>
              <div class="ml-2">
                <a-dropdown placement="bottomLeft" :get-popup-container="(trigger) => trigger.parentNode" destroy-popup-on-hide>
                  <template #overlay>
                    <a-menu class="text-center">
                      <a-menu-item v-for="(action, i) in actionArray" :key="i + '-' + item.brId">
                        <BaseButton :disabled="action.disabled" size="small" type="link" @click="onClickVisit(item, action.state)">
                          {{ action.title }}
                        </BaseButton>
                        <!-- + (item.queueNo || '') -->
                      </a-menu-item>
                    </a-menu>
                  </template>
                  <div class="px-2 py-1 hover:bg-slate-200 rounded">
                    <MoreOutlined class="text-base" />
                  </div>
                </a-dropdown>
              </div>
            </div>
          </div>
        </div>
      </template>
    </BaseList>
    <MovePatientModal v-model:open="referralOpen" :row-data="selectedItem" @success="search()" />
    <a-form-item v-if="state !== 3" label="挂号类别" class="w-full mb-0 mt-2" :label-col="{ style: { width: '64px' } }">
      <!-- <SelectRegistType v-model:value="ghlbid" /> -->
      <a-select v-model:value="ghlbid" placeholder="请选择">
        <a-select-option v-for="item in categoryList" :key="item" :value="item.ghlbid">{{ item.ghlb }}</a-select-option>
      </a-select>
    </a-form-item>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { MoreOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { checkPatientStatus } from '@/utils/tools'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import BaseList from '@/components/BaseList'
// import SelectRegistType from '@/components/SelectRegistType'
import SearchComb from '@/components/SearchComb'
import LabelValue from '@/components/LabelValue'
import useUserStore from '@/store/user'
import useStore from '../../store'
import MovePatientModal from './MovePatientModal.vue'

const store = useStore()
const { empId } = useUserStore()
const searchState = ref({})
const loading = ref(true)
const dataSource = ref([])
const selectedItem = ref()
const searchButton = ref([])
const isShowOperations = ref(false)
const actionArray = ref([])
const state = ref(0)
const ghlbid = ref('')
const categoryList = ref([])
const stateArr = ref([0, 1])
const referralOpen = ref(false)
const referralData = ref({})

const onSelect = async (item) => {
  if (item.tabStatus !== '手术') {
    const isCheck = await checkPatientStatus(item.jzbh)
    if (!isCheck) return
  }
  selectedItem.value = item
  store.currentPatient = item
}

const search = () => {
  if (ghlbid.value) {
    queryList(false)
    getRegistereCount()
  }
}

const queryList = async (isSelect = true) => {
  loading.value = true
  const {
    code,
    data = [],
    msg
  } = await post(
    state.value === 5 ? '/outp/mzys/getSurgeryAppointmentsPatients' : '/outp/mzys/getOutpRecordInfoList',
    {
      pyjm: searchState.value?.searchKey,
      stdate: searchState.value?.startDate ? searchState.value?.startDate : dayjs().format('YYYY-MM-DD'),
      eddate: searchState.value?.endDate ? searchState.value?.endDate : dayjs().format('YYYY-MM-DD'),
      ghys: searchState.value?.ghys,
      ghlbid: state.value !== 3 ? ghlbid.value : undefined,
      ghzts: state.value === 5 ? undefined : stateArr.value,
      statusList: state.value === 5 ? ['0', '1', '2'] : undefined,
      type: 1,
      checkCallNumberConfig: state.value === 5 ? undefined : store.isCallConfig
    },
    {
      loading: true
    }
  )
  loading.value = false
  if (code !== 0) return message.error(msg || '查询失败')
  dataSource.value = data.map((item) => {
    return {
      ...item,
      tabStatus: searchButton.value.find((x) => x.state === state.value)?.title
    }
  })
  if (data.length) {
    if (store.isCallConfig) {
      if (isSelect) {
        const res = await post(`/outp/doctorQueue/getDoctorQueueInfo`, { ghlbId: ghlbid.value })
        if (res.code !== 0) message.error(res.msg || '获取叫号队列失败')
        store.callConfigData = res.data || {}
        const select = data.filter((item) => {
          return item.jzbh === store.callConfigData.jzbh
        })
        if (select && select.length > 0) {
          selectedItem.value = select[0]
          store.currentPatient = select[0]
        } else {
          selectedItem.value = {}
          store.currentPatient = {}
        }
      }
    } else {
      if (isSelect) {
        selectedItem.value = data[0]
        store.currentPatient = data[0]
      }
    }
  } else {
    selectedItem.value = {}
    store.currentPatient = {}
  }
}
const getRegistereCount = async () => {
  const res = await post('/outp/outpComprehensive/getOutpRegistereCountList', {
    stdate: searchState.value?.startDate ? searchState.value?.startDate : dayjs().format('YYYY-MM-DD'),
    eddate: searchState.value?.endDate ? searchState.value?.endDate : dayjs().format('YYYY-MM-DD'),
    ghys: searchState.value?.ghys,
    ghlbid: ghlbid.value,
    type: 1
  })
  if (res.code !== 0) return message.error(res.msg)
  if (isShowOperations.value) {
    searchButton.value = [
      { state: 0, title: '候诊中' },
      { state: 3, title: '已完诊' },
      { state: 4, title: '待回诊' },
      { state: 5, title: '手术' }
    ]
  } else {
    searchButton.value = [
      { state: 0, title: '候诊中' },
      { state: 3, title: '已完诊' },
      { state: 4, title: '待回诊' }
    ]
  }
  searchButton.value = searchButton.value.map((item) => {
    if (item.state === 0) item.count = res.data.hz //候诊中
    if (item.state === 3) item.count = res.data.ywz //已完诊
    if (item.state === 4) item.count = res.data.dhz //待回诊
    if (item.state === 5) item.count = res.data.ssrs //手术
    return item
  })
  if (!store.isCallConfig) {
    searchButton.value = searchButton.value.filter((item) => {
      return item.state !== 4
    })
  }
}

const onChangeActive = () => {
  store.currentPatient = {}
  selectedItem.value = {}
  stateArr.value = state.value === 0 ? [state.value, 1] : [state.value]
  queryList(false)
  getActive()
}

const onClickVisit = async (row, val) => {
  //转诊
  if (val === 5) {
    selectedItem.value = row
    referralOpen.value = true
  } else if (val === 6) {
    //呼叫
    const res1 = await post(`/outp/doctorQueue/getDoctorQueueInfo`, { ghlbId: ghlbid.value })
    if (res1.code !== 0) message.error(res1.msg || '获取叫号队列失败')
    const res = await post('/outp/doctorQueue/doCallChosen', {
      QueueNo: row.queueNo,
      // QueueId: store.callConfigData.queueId
      QueueId: res1.data?.queueId
    })
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    queryList(true)
    getRegistereCount()
    window.openExe?.callUpdSend(JSON.stringify(res.data)) //调用winform叫号
  } else {
    const res = await post('/outp/mzys/modifyPatientClinicStatus', {
      // qmQrId: row.qmQrId,
      ghzt: val,
      jzbh: row.jzbh,
      ysbh: row.ysbh ? row.ysbh : ''
    })
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    queryList(true)
    getRegistereCount()
    window.openExe?.callUpdSend(JSON.stringify(res.data)) //调用winform叫号
  }
}
const getActive = () => {
  // if (state.value === 0 || state.value === 3 || state.value === 4) {
  //   actionArray.value = searchButton.value.filter((x) => {
  //     //过滤掉当前状态及手术
  //     return x.state !== state.value && x.state !== 5
  //   })
  //   actionArray.value.push({ state: 6, title: '呼叫' })
  // } else {
  //   actionArray.value = searchButton.value.filter((x) => {
  //     //过滤掉当前状态
  //     return x.state !== state.value
  //   })
  // }
  // actionArray.value.push({ state: 5, title: '转诊' })
  if (state.value === 0) {
    //候诊中
    actionArray.value = [
      { state: 3, title: '已完诊', disabled: false },
      { state: 4, title: '待回诊', disabled: false, isHide: store.isCallConfig ? false : true },
      { state: 6, title: '呼叫', disabled: false, isHide: store.isCallConfig ? false : true },
      { state: 5, title: '转诊', disabled: false }
    ]
  } else if (state.value === 3) {
    //已完诊
    actionArray.value = [
      { state: 0, title: '候诊中', disabled: store.isCallConfig ? true : false },
      { state: 4, title: '待回诊', disabled: false, isHide: store.isCallConfig ? false : true },
      { state: 6, title: '呼叫', disabled: true, isHide: store.isCallConfig ? false : true },
      { state: 5, title: '转诊', disabled: store.isCallConfig ? true : false }
    ]
  } else if (state.value === 4) {
    //待回诊
    actionArray.value = [
      { state: 0, title: '候诊中', disabled: store.isCallConfig ? true : false },
      { state: 3, title: '已完诊', disabled: false },
      { state: 6, title: '呼叫', disabled: true, isHide: store.isCallConfig ? false : true },
      { state: 5, title: '转诊', disabled: store.isCallConfig ? true : false }
    ]
  } else {
    //手术
    actionArray.value = [
      { state: 0, title: '候诊中', disabled: store.isCallConfig ? true : false },
      { state: 3, title: '已完诊', disabled: false },
      { state: 4, title: '待回诊', disabled: false, isHide: store.isCallConfig ? false : true },
      { state: 5, title: '转诊', disabled: store.isCallConfig ? true : false }
    ]
  }
  actionArray.value = actionArray.value.filter((item) => {
    return !item.isHide
  })
}

const handlerReferral = async (jzbh) => {
  const res = await post('/outp/mzys/getPatientReferral', { jzbh })
  if (res.code !== 0) return message.error(res.msg)
  referralData.value = res.data
}
const getDoctorFee = async () => {
  const { code, data = [] } = await post('/outp/mzdj/getSchedulingDocterList', { empId })
  if (code !== 0) return
  ghlbid.value = data[0]?.ghlbId || ''
}

// 挂号类别
const getCategoryData = async () => {
  const { code, data } = await post('/operation/opex/getRegisterDictInfoList', {
    mcbh: '',
    pageNum: 1,
    pageSize: 9999,
    requiredDoctor: 0,
    ztflag: 0, // 0有效，1无效
    ghlbid: ghlbid.value
  })
  if (code === 0) {
    categoryList.value = data
    if (!ghlbid.value) ghlbid.value = data[0]?.ghlbid
  }
}
const getCallConfig = async () => {
  const { code, data, msg } = await post(`/outp/dictQueue/checkCallNumberConfig`, { ghlbid: ghlbid.value })
  if (code !== 0) return message.error(msg || '获取叫号配置失败')
  store.isCallConfig = data
}

watch(ghlbid, async (val) => {
  if (val) {
    store.ghlbid = val
    await getCallConfig()
    getActive()
    setTimeout(function () {
      getRegistereCount()
      queryList(false)
    }, 200)
  }
})
onMounted(async () => {
  isShowOperations.value = getSystemConfig('IS_OUTP_DOCTOR_PATIENTLIST_OPERATION') === '1' ////门诊医生站_患者列表_是否启用手术频道
  await getDoctorFee()
  getCategoryData()
  // getActive()
})
defineExpose({
  onSelect,
  queryList,
  getRegistereCount
})
</script>

<style lang="less" scoped>
// .active-parent {
//   line-height: 34px;
//   border: 1px solid #d9d9d9;
// }
// .active-search {
//   border-right: 1px solid #d9d9d9;
// }
// .active-search:last-child {
//   border-right: 0;
// }
// .active-button {
//   color: #fff;
//   background-color: var(--primary-color);
// }
// .visit-state:hover {
//   color: #fff;
//   background-color: var(--primary-color);
// }
.radio-style {
  display: flex;
  :deep(.ant-radio-button-wrapper) {
    // width: 33.3%;
    flex: 1;
    padding: 0;
    text-align: center;
  }
}
</style>
